package com.lw.syn;

/**
 * @author LW
 * @2020/8/18 13:55
 */
public class synBuyticket {


    public static void main(String[] args) {
        sycBuyTicket buyTicket = new sycBuyTicket();
        new Thread(buyTicket,"星星").start();
        new Thread(buyTicket,"小狗").start();
        new Thread(buyTicket,"黄牛").start();


    }


}


class sycBuyTicket implements Runnable{

    //票数
    private int ticketNums = 10;
    boolean flag = true;
    @Override
    public void run() {
        //买票
        while (flag){
            buy();
        }

    }


    //加synchronized同步方法，  同步方法锁的是  类对象sycBuyTicket本身
    private synchronized void buy(){
        //判断是否有票
        if(ticketNums<=0){
            return;
        }
        try {//线程同步时，须要加sleep不然会一直跑第一个线程
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //买票
        System.out.println(Thread.currentThread().getName()+"拿到了****"+ticketNums--);
    }
}
